package com.weibo.tool;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.List;
import java.util.Objects;

@Slf4j
public class HttpTool {

    private static String cookie = "SCF=AioszgWyKtUEm83Kh8saWMoWeM-KxGh4y_OJkau6cT-adKjTofpQk0iLvV_zGUUS04-3ImUnGRH3_hM4-F2Elo0.; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WFanUgPp.Fy2ksXxgpru6O25JpX5KMhUgL.Fo-RSo2ESoepe022dJLoI7LjdcUydLvadJ-t; ALF=1735386798; SUB=_2A25KTCn-DeRhGeNG7VMT9i3NyD2IHXVpICM2rDV8PUJbkNB-LVTdkW1NSy8XmjcmRUlHF9CbwyaltQPiZp4No4b8; SINAGLOBAL=663602029782.2042.1733221976260; _s_tentry=weibo.com; Apache=6902041028460.064.1733315488082; ULV=1733315488089:3:3:3:6902041028460.064.1733315488082:1733233769784";
    static CloseableHttpClient httpclient = HttpClients.createDefault();
    static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36";

    static HttpGet get = new HttpGet();
    static HttpPost post = new HttpPost();

    public static void main(String[] args) throws Exception {
        post("",null,null);
    }
    // 改id  改签名
    //14591
    //private static String entityStr = "{\"p\":\"w\",\"Sign\":\"RootSign\",\"active_time_id\":\"14591\",\"contact_phone\":\"18310365230\",\"alternate\":\"\",\"toi_cardtype_id\":1,\"spot\":0,\"person\":[{\"toi_cardtype_id\":1,\"toi_username\":\"蒋汪洋\",\"toi_card_num\":\"332624199104240010\"}],\"notes\":\"\",\"children\":[],\"toi_unit\":\"\",\"uid\":\"P%3AhWT596H%2B3%2BICj%2BRVlOzsdA%3D%3D\",\"_sign\":[\"Az2vjNwtgm8ip8EgHaIPTkEbNOpv26IWXCb//6V1BH3J0Vj3JTCTpQcgp6gRhPrMGpIR0ispLYhq2SqUWCEB9RFQdadoTKttJV19GTL2fdiIA7nGvjDHGmVxjmI/LyAdjlbMFr/l9AFtct2Vo2c7v8WQEdHe5jgMVJnWSGQLg9j8SFEZRFnstZfvfKuFkOBm7yNMrbfLRrj3FYOhc2VEILf5TMBAVC3tUw/BuaGqnYqffriJ6GXXXifIZfIp+ATlH8lcQgWUslp8LJ0KrhDt8cYiUyDEP8agP+bJN4JSIHVybspN0NJAHpIkrmwG15Jc2qTo0Y4q4XtaPT/uD758qw==\"],\"api_token\":\"efd69a911cb0df16522d0c9349273914\"}";
    static{
        post.setHeader("sec-fetch-site","same-origin");
        post.setHeader("accept-encoding","gzip, deflate, br");
        post.setHeader("referer","https://api.weibo.com/chat");
        post.setHeader("accept","application/json, text/plain, */*");
        post.setHeader("sec-fetch-mode","cors");
        post.setHeader("accept-language","zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        post.setHeader("user-agent","Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36 Edg/92.0.902.67");
        post.setHeader("sec-fetch-dest","empty");
        post.setHeader("origin","https://api.weibo.com");
        post.setHeader("sec-ch-ua-mobile","?1");
        post.setHeader("content-type","application/x-www-form-urlencoded");
        post.setHeader("Cookie",cookie);

        get.setHeader("sec-fetch-site","same-origin");
        get.setHeader("accept-encoding","gzip, deflate, br");
        get.setHeader("referer","https://api.weibo.com/chat");
        get.setHeader("accept","application/json, text/plain, */*");
        get.setHeader("sec-fetch-mode","cors");
        get.setHeader("accept-language","zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
        get.setHeader("user-agent","Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Mobile Safari/537.36 Edg/92.0.902.67");
        get.setHeader("sec-fetch-dest","empty");
        get.setHeader("origin","https://api.weibo.com");
        get.setHeader("sec-ch-ua-mobile","?1");
        get.setHeader("Cookie",cookie);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000) // 连接超时时间，单位毫秒
                .setSocketTimeout(3000)  // 读取超时时间，单位毫秒
                .build();
        post.setConfig(requestConfig);
        get.setConfig(requestConfig);

    }
    public static Object post(String url, JSONObject data, List<NameValuePair> urlParameters) throws Exception {

        CloseableHttpResponse response ;
        post.setURI(new URI(url));

        if(Objects.nonNull(data)){
            post.setEntity(new StringEntity(JSON.toJSONString(data), ContentType.APPLICATION_FORM_URLENCODED));
        }
        if(Objects.nonNull(urlParameters)){
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, "UTF-8");
            post.setEntity(entity);
        }

        try{
            response = httpclient.execute(post);
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            if(body.startsWith("[")){
                JSONArray resultArr = JSONArray.parseArray(body);
                return resultArr;
            }else if(body.startsWith("{")){
                JSONObject result = JSONObject.parseObject(body);
                return result;
            }else {
                return body;
            }

            //result = JSONArray.parseArray(body);
            //System.out.println(result);
        }catch (Exception e){
            log.error("请求接口出错"+e.toString());
            e.printStackTrace();
        }

        return null;
    }

    public static Object get(String url) throws Exception {

        CloseableHttpResponse response ;
        get.setURI(new URI(url));

        try{
            response = httpclient.execute(get);
            String body = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            if(body.startsWith("[")){
                JSONArray resultArr = JSONArray.parseArray(body);
                return resultArr;
            }else if(body.startsWith("{")){
                JSONObject result = JSONObject.parseObject(body);
                return result;
            }

            //result = JSONArray.parseArray(body);
            //System.out.println(result);
        }catch (Exception e){
            log.error("请求接口出错"+e.toString());
            e.printStackTrace();
        }

        return null;
    }

}